package fileshow

import (
	"fmt"
	"github.com/spf13/afero"
	"gitlab.local/DO-module/new-filemanage-module/src/core/sqlitedb/sqlitemodel"
	"gitlab.local/golibrary/user"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

func (fs *FileShow) FileGenerator(directory string) <-chan string {
	fileChan := make(chan string)

	go func() {
		defer close(fileChan)
		osf := afero.NewOsFs() // 使用操作系统文件系统
		files, err := afero.ReadDir(osf, directory)
		if err != nil {
			fmt.Println("Error:", err)
			return
		}

		for _, file := range files {
			fileChan <- file.Name()
		}
	}()

	return fileChan
}

func (fs *FileShow) PaginateFiles(fileChan <-chan string, page, limit int) []string {
	startIndex := (page - 1) * limit
	endIndex := startIndex + limit

	var files []string
	counter := 0

	for file := range fileChan {
		if counter >= endIndex {
			break
		}
		if counter >= startIndex {
			files = append(files, file)
		}

		counter++
	}

	return files
}

// FolderEmpty 文件夹是否为空
// return true为空
func (fs *FileShow) FolderEmpty(path string) (bool, error) {
	dir, err := os.ReadDir(path)
	if err != nil {
		return false, err
	}
	le := len(dir)
	if le == 0 {
		return true, nil
	}
	if le == 1 {
		compile, err := regexp.Compile(`^/Volume\d+/(@usb/usbshare\d+|@iso|@iscsi|@eSATA|[^/]+)/#recycle/?$`) //匹配回收站
		if err != nil {
			return false, nil
		}
		if compile.MatchString(filepath.Join(path, dir[0].Name())) {
			return true, nil
		}
	}
	return false, nil
}

func (fs *FileShow) HandleGetUserOrGroup() (interface{}, error) {
	res, e := fs.GetUserOrGroup()
	if e != nil {
		return nil, e
	}

	var data struct {
		Users  []string `json:"users"`
		Groups []string `json:"groups"`
	}
	users := make(map[string]int)
	for k, v := range res {
		data.Groups = append(data.Groups, k)
		for _, val := range v {
			users[val] = 0
		}
	}
	for k := range users {
		data.Users = append(data.Users, k)
	}
	return data, nil
}

func (fs *FileShow) GetUserOrGroup() (map[string][]string, error) {
	var groupData, userData []sqlitemodel.UserTable
	db := fs.dbGetter.DbGet()
	_ = db.Where("password=?", "group").Select("username").Find(&groupData)
	_ = db.Where("password not in ?", []string{"group", "adnet", "adgroup"}).Select("username").Find(&userData)
	userOrGroup := make(map[string][]string)
	for _, v := range groupData {
		gName := strings.TrimPrefix(v.Username, "@")
		_, err := user.LookupGroup(gName)
		if err != nil {
			continue
		}
		userOrGroup[gName] = make([]string, 0)
	}
	for _, v := range userData {
		//如果为admin,不为超级管理员则跳过
		if v.Username == "admin" {
			continue
		}
		_, err := user.Lookup(v.Username)
		if err != nil {
			continue
		}
		for _, val := range fs.UserGroups(v.Username) {
			if _, b := userOrGroup[val]; b {
				userOrGroup[val] = append(userOrGroup[val], v.Username)
			}
		}
	}
	return userOrGroup, nil
}

func (fs *FileShow) UserGroups(uname string) []string {
	groups := make([]string, 0)
	lookup, err := user.Lookup(uname)
	if err != nil {
		return groups
	}
	ids, err := lookup.GroupIds()
	if err != nil {
		return groups
	}
	for _, v := range ids {
		id, err := user.LookupGroupId(v)
		if err != nil {
			continue
		}
		groups = append(groups, id.Name)
	}
	return groups
}
